package com.duanjw.springcloud.consumer.web;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 消费者 controller
 *
 * @author duanjw
 */
@RestController
public class ConsumerController {

    private final LoadBalancerClient loadBalancerClient;
    private final RestTemplate restTemplate;
    private final RestTemplate restTemplateRibbon;

    public ConsumerController(LoadBalancerClient loadBalancerClient, RestTemplate restTemplate, RestTemplate restTemplateRibbon) {
        this.loadBalancerClient = loadBalancerClient;
        this.restTemplate = restTemplate;
        this.restTemplateRibbon = restTemplateRibbon;
    }

    /**
     * 通过 LoadBalanceClient 和 RestTemplate 的组合调用其他服务
     * <p>
     * 请求地址：curl localhost:7004/load-balancer
     *
     * @return
     */
    @GetMapping("load-balancer")
    public String loadBalancer() {
        // 根据服务名从一个或多个服务列表中获取一个服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider");
        String path = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), "LoadBalancerClient");
        return restTemplate.getForObject(path, String.class);
    }

    /**
     * 使用带有 LoadBalance 的 RestTemplate 调用其他服务
     * <p>
     * 请求地址：curl localhost:7004/rest-template-load-balance
     *
     * @return
     */
    @GetMapping("rest-template-load-balance")
    public String restTemplateLoadBalance() {
        String path = String.format("http://%s/echo/%s", "provider", "RestTemplateLoadBalance");
        return restTemplateRibbon.getForObject(path, String.class);
    }
}